<template>
    <div>
        <!--对数据做查询-->
        <el-row>
            <el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline">
                <el-form-item label="用户ID">
                    <el-input v-model="formInline.userId" placeholder="用户ID"></el-input>
                </el-form-item>
                <el-form-item label="用户名称">
                    <el-input v-model="formInline.loginName" placeholder="用户名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
                <el-button
                        type="primary"
                        @click="handleAdd">添加用户
                </el-button>
            </el-form>
        </el-row>
        <!--表格内容-->
        <el-row>
            <el-table
                    :data="tableData"
                    style="width: 100%" border>
                <el-table-column
                        prop="userId"
                        label="用户ID">
                </el-table-column>
                <el-table-column
                        prop="loginName"
                        label="真实名称">
                </el-table-column>
                <el-table-column
                        prop="userName"
                        label="登陆账号">
                </el-table-column>
                <el-table-column
                        prop="deptName"
                        label="所在部门">
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="用户状态"
                        :formatter="roleStatus">
                </el-table-column>
                <el-table-column
                        prop="email"
                        label="邮箱">
                </el-table-column>
                <el-table-column
                        prop="status"
                        label="用户状态">
                </el-table-column>
                <el-table-column
                        prop="phonenumber"
                        label="手机号">
                </el-table-column>
                <el-table-column
                        prop="sex"
                        label="性别">
                </el-table-column>
                <!--<el-table-column
                        prop="avatar"
                        label="头像">
                </el-table-column>-->
                <el-table-column
                        prop="loginIp"
                        label="最后登录IP">
                </el-table-column>
                <el-table-column prop="loginDate" label="最后登陆时间">
                    <!--<template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        <span style="margin-left: 10px">{{ scope.row.loginDate | loginDate("yyyy-mm-dd hh:mm:ss")  }}</span>
                    </template>-->
                </el-table-column>
                <!--<el-table-column
                        prop="createTime"
                        label="创建日期">
                </el-table-column>
                <el-table-column
                        prop="updateBy"
                        label="更新者">
                </el-table-column>
                <el-table-column
                        prop="updateTime"
                        label="更新时间">
                </el-table-column>-->
                <el-table-column
                        prop="remark"
                        label="备注">
                </el-table-column>
                <el-table-column label="操作" width="330">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button size="mini"
                                   type="danger" @click="deleteUser(scope.$index, scope.row)">删除
                        </el-button>
                        <el-button size="mini"
                                   type="info" @click="editRole(scope.$index, scope.row)">修改角色
                        </el-button>
                        <el-button size="mini"
                                   type="info" @click="resetPassword(scope.$index, scope.row)">重置密码
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!--分页定义-->
        <el-row>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,3,5,10,20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-row>
        <!--编辑或添加对话框-->
        <el-dialog
                :title="title"
                :visible.sync="addDialogVisible"
                width="30%">
            <el-form :model="editOrAddForm" ref="editOrAddForm" :rules="rules" label-width="50px"
                     class="demo-ruleForm">
                <el-input v-model="editOrAddForm.userId" style="display: none"></el-input>
                <el-form-item label="名字" prop="loginName">
                    <el-input v-model="editOrAddForm.loginName"></el-input>
                </el-form-item>
                <el-form-item label="账号" prop="userName">
                    <el-input v-model="editOrAddForm.userName"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <el-cascader
                            v-model="value"
                            :options="options"
                            :props="{ expandTrigger: 'hover' }"
                            @change="handleChange" style="width: 350px">
                    </el-cascader>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editOrAddForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="phonenumber">
                    <el-input v-model="editOrAddForm.phonenumber"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editOrAddForm.sex">
                        <el-radio :label="`0`" border>男</el-radio>
                        <el-radio :label="`1`" border>女</el-radio>
                        <el-radio :label="`2`" border>未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="editOrAddForm.status">
                        <el-radio :label="`0`" border>正常</el-radio>
                        <el-radio :label="`1`" border>禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editOrAddForm.remark"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="closeEditOrAddDialog">取 消</el-button>
            <el-button type="primary" @click="submitEditOrAddDialog('editOrAddForm')">确 定</el-button>
        </el-dialog>
        <!--编辑用户角色对话框-->
        <el-dialog
                :title="titlea"
                :visible.sync="editDialogVisible"
                width="30%">
            <el-input :v-model="userId" style="display: none"></el-input>
            <el-tree
                    :data="treeData"
                    :show-checkbox="true"
                    node-key="id"
                    ref="tree"
                    :props="defaultProps">
            </el-tree>
            <el-button @click="closeTreeDialog">取 消</el-button>
            <el-button type="primary" @click="submitTreeDialog()">确 定</el-button>

        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            const validateContract = (rule, value, callback) => {
                if (this.editOrAddForm.userId === undefined) {
                    this.editOrAddForm.userId = 0;
                }
                this.$http.get("/ss/user/checkName?userName=" + value + "&userId=" + this.editOrAddForm.userId)
                    .then((response) => {
                        if (response.data.resultCode === 5000) {
                            callback(new Error('该名称已存在！'));
                        } else {
                            callback();
                        }
                    })
            };
            return {
                tableData: [],
                currentPage: 1,//当前页
                total: 100, //总数据量
                formInline: {loginName: '', userId: ''},
                pageSize: 5,//每页数据量
                addDialogVisible: false, //对话框的状态，默认关闭
                editDialogVisible: false,
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                titlea: '',
                true: true,
                title: '',
                userId: '',
                editOrAddForm: {
                    userId: '',
                    loginName: '',
                    userName: '',
                    password: '',
                    deptId: '',
                    parentId: '',
                    deptName: '',
                    email: '',
                    phonenumber: '',
                    sex: '',
                    status: '',
                    remark: '',
                },
                value: [],
                options: [],
                rules: {
                    loginName: [
                        {required: true, message: '请输入用户名称', trigger: 'blur'},
                    ],

                    sex: [
                        {required: true, message: '请选择性别', trigger: 'blur'},
                    ],
                    userName: [
                        {required: true, message: '请输入登陆账号', trigger: 'blur'},
                        {trigger: 'blur', validator: validateContract}//自定义验证:调方法
                    ],
                    phonenumber: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        { pattern: /^1\d{10}$/, message: '请输入正确的号码格式', trigger: 'blur' }
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        { pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: '请输入正确的邮箱格式', trigger: 'blur' }
                    ],
                    status: [
                        {required: true, message: '请选择状态', trigger: 'blur'},
                    ],
                },

            }
        },
        // 初始化数据  mounted()
        created: function () {
            this.loadData();
        },
        methods: {
            //封装数据请求
            loadData() {
                var _this = this;
                this.$http.post("/ss/user/queryAll?pageNo=" + this.currentPage + "&pageSize=" + this.pageSize, this.formInline).then((response) => {
                    _this.tableData = response.data.t.list;
                    _this.total = response.data.t.total;

                })
            },
            //处理编辑
            async handleEdit(index, row) {
                let rowData = JSON.parse(JSON.stringify(row));
                this.value = [];
                this.editOrAddForm = {};
                this.title = '编辑用户信息';
                var _this = this;
                this.$http.post("/ss/dept/queryAll", {}).then((response) => {
                    _this.options = response.data.t;
                });
                this.editOrAddForm = rowData;
                this.value = this.editOrAddForm.deptId;

                this.addDialogVisible = true;
            },
            //处理删除
            deleteUser(index, row) {
                let rowData = JSON.parse(JSON.stringify(row));
                this.$confirm('此操作将删除该员工, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete("/ss/user/deleteById?userId=" + rowData.userId).then((response) => {
                        if (response.data.resultCode === 2000) {
                            this.$message({
                                message: '修改成功！',
                                type: 'success'
                            });
                            this.loadData();
                            this.addDialogVisible = false;
                        } else {
                            this.$message({
                                message: response.data.resultMessage,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //处理重置密码
            resetPassword(index, row){
                let rowData = JSON.parse(JSON.stringify(row));
                this.$confirm('此操作将重置该员工密码, 是否继续?(重置后密码为123456)', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.get("/ss/user/resetPassword?userId=" + rowData.userId).then((response) => {
                        if (response.data.resultCode === 2000) {
                            this.$message({
                                message: '重置成功！',
                                type: 'success'
                            });
                            this.loadData();
                            this.addDialogVisible = false;
                        } else {
                            this.$message({
                                message: response.data.resultMessage,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });
                });
            },
            //处理添加
            handleAdd() {

                this.title = '添加用户';
                var _this = this;
                this.$http.post("/ss/dept/queryAll", {}).then((response) => {
                    _this.options = response.data.t;
                });
                this.value = [];
                this.editOrAddForm = {};
                this.addDialogVisible = true;
            },
            //处理修改用户角色
           async editRole(index, row){
                let rowData = JSON.parse(JSON.stringify(row));
                this.treeData = [];
                this.titlea = '用户角色管理';
                this.userId = rowData.userId;
                //查找全部role
               await this.$http.get("/ss/role/queryAllRoleTree").then((response) => {
                    this.treeData = response.data.t;
                });
                //查找某个用户所拥有的角色
               this.$http.get("/ss/role/queryRoleIdForTreeByUserId?userId=" + rowData.userId).then((response) => {
                    // 清空tree的选择
                    this.$refs.tree.setCheckedKeys([]);
                    let noHasChildrenMenuTree = response.data.t;
                    noHasChildrenMenuTree.forEach(element => {
                        // 设置数组勾选，查出来所有的菜单
                        this.$refs.tree.setChecked(element, true, false)
                    })
                });
                this.editDialogVisible = true;
            },
            //分页 每页数量变化时处理
            handleSizeChange(val) {
                this.pageSize = val;
                this.loadData();
            },
            //分页 第几页变化时处理
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },
            //点击查询方法
            onSubmit() {
                this.currentPage = 1;
                this.loadData();
            },
            //判断角色状态
            roleStatus(row) {
                if (row.status === "0") {
                    return "正常"
                } else {
                    return "禁用"
                }
            },
            closeEditOrAddDialog() {
                this.addDialogVisible = false;
            },
            //编辑和添加提交
            submitEditOrAddDialog(editOrAddForm) {
                this.$refs[editOrAddForm].validate((valid) => {
                    if (valid) {
                        this.editOrAddForm.deptId = this.value[this.value.length - 1];
                        if (this.editOrAddForm.userId >= 1) {
                            this.$http.put("/ss/user/update", this.editOrAddForm).then((response) => {
                                if (response.data.resultCode === 2000) {
                                    this.$message({
                                        message: '修改成功！',
                                        type: 'success'
                                    });
                                    this.loadData();
                                    this.addDialogVisible = false;
                                } else {
                                    this.$message({
                                        message: response.data.resultMessage,
                                        type: 'error'
                                    });
                                }
                            })
                        } else {
                            this.$http.post("/ss/user/insert", this.editOrAddForm).then((response) => {
                                if (response.data.resultCode === 2000) {
                                    this.$message({
                                        message: '添加成功！',
                                        type: 'success'
                                    });
                                    this.loadData();
                                    this.addDialogVisible = false;
                                } else {
                                    this.$message({
                                        message: response.data.resultMessage,
                                        type: 'error'
                                    });
                                }
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            //重置表单
            resetForm() {
                this.formInline = {};
                this.loadData();
            },
            closeTreeDialog() {
                this.editDialogVisible = false;
            },
            submitTreeDialog() {
                let arr = [];
                arr.push(...this.$refs.tree.getCheckedKeys());
                let userRole={
                    userId: this.userId,
                    arr: arr
                };
                this.$http.post("/ss/userRole/insert", userRole).then((response) => {
                    if (response.data.resultCode === 2000) {
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                    } else {
                        this.$message({
                            message: response.data.resultMessage,
                            type: 'error'
                        });
                    }
                });
                this.loadData();
                this.editDialogVisible = false;
            }
            , handleChange(value) {
            },

        }
    }
</script>
<style>

</style>